import { createFileRoute } from "@tanstack/react-router";
import { Check, Mic, Pause, Play } from "lucide-react";
import { useState } from "react";
import Button from "@/components/Button";
import useAudioRecorder from "@/hooks/audio-recorder";
import useKeysPress from "@/hooks/keys-press";

export const Route = createFileRoute("/audio/recorder")({
  head: () => ({
    meta: [{ title: "Audio Recorder" }, { name: "description", content: "Audio Recorder" }],
  }),
  component: RouteComponent,
});

function RouteComponent() {
  const [audioUrl, setAudioUrl] = useState<string | null>(null);
  const audio = useAudioRecorder({
    onOk: (audioBlob) => {
      const url = URL.createObjectURL(audioBlob);
      setAudioUrl(url);
    },
    onError: (e) => {
      console.error("error", e);
    },
  });

  const handleClick = () => {
    if (audio.status === "inactive") {
      setAudioUrl(null);
      audio.start();
    } else {
      audio.stop();
    }
  };

  const handlePause = () => {
    switch (audio.status) {
      case "recording":
        audio.pause();
        break;
      case "paused":
        audio.resume();
        break;
    }
  };

  useKeysPress({ key1: "n", key2: "m", onAllPress: handleClick });

  return (
    <div>
      <div className="p-4 flex gap-4">
        <Button shape="circle" variant="outline" onClick={handleClick}>
          {audio.status === "inactive" ? <Mic size="18px" /> : <Check size="18px" />}
        </Button>
        <Button shape="circle" variant="outline" onClick={handlePause} disabled={audio.status === "inactive"}>
          {audio.status === "recording" ? <Pause size="18px" /> : <Play size="18px" />}
        </Button>
        {audioUrl && (
          <audio controls src={audioUrl}>
            <track kind="captions" />
          </audio>
        )}
      </div>
      <div>
        <small>
          点击按钮或者同时按下 <kbd>m</kbd>+<kbd>n</kbd> 键
          {audio.status === "inactive" ? "开始" : audio.status === "recording" ? "完成" : "xx"}
          录音
        </small>
      </div>
    </div>
  );
}
